import { getAppIDInfo, getAllAppIDInfos, IAppBaseInfo } from "@/config/template";
import ServiceInfoManager from "./ServiceInfoManager";

const allAppInfos = getAllAppIDInfos();

export async function getDeviceShareUrlByAppInfo({ appId }: IAppBaseInfo) {
  const aepUrl = await ServiceInfoManager.getAepApiUrl();
  return `${aepUrl}app/${appId}/shareDevice/index.html`;
}

export function getDeviceShareUrl() {
  const { appId } = getAppIDInfo();
  const aepUrl = ServiceInfoManager.getAepApiUrlSync();
  return `${aepUrl}app/${appId}/shareDevice/index.html`;
}

export async function getDeviceShareLinkByAppInfo({ appInfo, shareId }: { appInfo: IAppBaseInfo, shareId: string }) {
  const url = await getDeviceShareUrlByAppInfo(appInfo);
  return `${url}?shareId=${shareId}`;
}

export function getDeviceShareLink(shareId: string) {
  const url = getDeviceShareUrl();
  return `${url}?shareId=${shareId}`;
}

function parseSearch(search: string): Record<string, string> {
  return (search.startsWith('?') ? search.slice(1) : search).split('&').reduce((obj, kv) => {
    const [k, v] = kv.split('=');
    return { ...obj, [k]: v };
  }, {})
}

export async function parseDeviceShareId(link: string): Promise<string | null> {
  let isShareUrl = false;
  let url = '';
  // 只要是同一个domain的iOS，安卓，微信app开头的，都可以接受分享
  for (let index = 0; index < allAppInfos.length; index++) {
    const appInfo = allAppInfos[index];
    // eslint-disable-next-line no-await-in-loop
    const shareUrl = await getDeviceShareUrlByAppInfo(appInfo);
    console.log('shareUrl', shareUrl);
    if (link.startsWith(shareUrl)) {
      isShareUrl = true;
      url = shareUrl;
      break;
    }
  }
  if (!isShareUrl) {
    return null;
  }
  const searchObj = parseSearch(link.slice(url.length));
  console.log('searchObj', searchObj);
  return searchObj.shareId || null;
}
